<template>
	<view class="map-container">	
		<!-- 地图区域 -->
		<view class="map-box">
			<map id="qqmap" 
			    ref="map1" 
				class="map-content" 
				:longitude="lng" 
				:latitude="lat" 
				:scale="16" 
				:show-location="true"
				@regionchange="regionchange" 
				:markers="covers"
				:style="{'width':windowWidth + 'px','height':windowHeight+'px'}">				
			</map>
			
			<!-- 中心点标记 -->
			<cover-image class="center-marker" :src="locPath" />
			
			<!-- 定位按钮 -->
			<cover-view class="control-panel">
				<cover-image class="location-btn" :src="resetBtnPath" @click="resetLocation"></cover-image>
			</cover-view>
		</view>
		
		<!-- 搜索栏 -->
		<view class="search-bar">
			<view class="city-selector" @click="openPopup()">
				<text class="city-text">{{selectorCityName || "选择城市"}}</text>
				<text class="city-arrow">▼</text>
			</view>
			<view class="divider"></view>
			<input 
				class="search-input" 
				v-model="keyword" 
				placeholder="请输入地址关键词"
				placeholder-class="placeholder"
				confirm-type="search"
				@confirm="searchLocAddress"
			/>
			<view class="search-btn" @click="searchLocAddress">
				<text class="btn-text">搜索</text>
			</view>
		</view>
		
		<!-- 城市选择弹窗 -->
		<view v-if="showPopup" class="popup-wrapper">
			<view class="popup-mask" @click="closedPopup"></view>			
			<u-select
				v-model="showPopup"
				mode="mutil-column-auto"
				@confirm="regionChange"
				:list="lists"
				confirm-color="#2979FF"
				cancel-color="#666666"
			></u-select>
		</view>
	</view>
</template>

<script>
	import {getLocation,getGeocoder} from "@/api/store";
	const QQMapWX = require('./config/qqmap-wx-jssdk.min.js')
	import HLSelectorCity from './hl-selector-city.vue'
	import area from "@/utils/area";
	export default {
		components : {
			HLSelectorCity
		},
		
		props:{
			locPath : {
				type : String
			},
			
			resetBtnPath : {
				type : String
			},
			iconPath : {
				type : String,
				default : '/static/images/iconPath.png'
				
			},
			
			mapKey : {
				type : String,
				default : 'IS6BZ-KFVHJ-YLSFJ-KWTJ4-IEMNE-YBF2S'
			},
			
			showCitySearch : {
				type : Boolean,
				default : true,
			}
			
		},
		data() {
			return {
				windowWidth : null,
				windowHeight:null,
				lng: null,
				lat: null,
				mapContext: null,
				loc_addressInfo: null,
				isInitialized: true,
				qqmapsdk : null,				
				showPopup: false, 				
				selectorCityName : null, //选择城市
				keyword : '', //输入框关键字搜索
				covers:[],
				lists: [],
				keyAddress:''

			}
		},
		
		created() {
			this.mapContext = uni.createMapContext('qqmap',this)			
			this.lists = area;
		},
		
		//第一次初始化用户位置信息
		mounted() {
			try {
				this.qqmapsdk = new QQMapWX({
					key: this.mapKey
				})
				var that = this;				
				const res = uni.getSystemInfoSync();	
				this.windowWidth = res.windowWidth;
				this.windowHeight = res.windowHeight*0.4;
				
				uni.showLoading({
					title: '获取位置中...',
					mask: true
				});
				uni.getLocation({
					type: "gcj02",
					geocode:true,
					isHighAccuracy: true,
					accuracy:"best",
					success: (res) => {
						console.log(88,res)
						uni.hideLoading()
						that.lng = res.longitude
						that.lat = res.latitude
						that.getAddressInfo(that.lat, that.lng)
						that.covers = [{latitude:that.lat, longitude:that.lng,"iconPath":that.iconPath}]
					},
					fail(e) {
						console.log('进入回调:fail'+JSON.stringify(e));
						uni.hideLoading()
						uni.showToast({
							title: '定位失败',
							icon: 'none'
						})
					},
					complete(e) {
						console.log('进入回调:complete'+ JSON.stringify(e) );
					}
				})
			} catch (e) {
				// error
				uni.hideLoading()
				uni.showToast({
					title: '初始化失败',
					icon: 'none'
				})
			}
		},
		methods: {
			//移动地图获取地址
			regionchange(e) {	
				this.mapContext.getCenterLocation({
                   success: (res)=>{				   
					   var lng = res.longitude;
					   var lat = res.latitude; 
					   this.getAddressInfo(lat,lng) 
				   }  
				})
			},
			//获取附近位置信息
			async getAddressInfo(latitude,longitude) {
				var that = this;
				let location = [latitude,longitude]
				
				//#ifdef APP-PLUS || H5 				
				const { code, data } = await getGeocoder({location:location,get_poi:1});	
				if(code == 1){
					let result  = data.result;
					that.selectorCityName = result.ad_info.city
								
					that.$emit('addressUpdate', {'result' :result.pois})
					
				}else{
				    uni.showToast({
						title: "查询失败",
						icon: 'none',
						duration: 3000
					})
				}
				
				// #endif
				
				//#ifdef MP-WEIXIN
				let stringLocation = location.toString()
				this.qqmapsdk.reverseGeocoder({
					location: stringLocation,
					get_poi: 1,
					success: res => {
						if (res.result.pois.length > 0) {
							that.selectorCityName = res.result.ad_info.city							
							let result = res.result.pois;
							that.$emit('addressUpdate', {'result' :result})
						}
						that.isInitialized = true
					},
					fail: err => {
						uni.showToast({
							title: err.toString,
							icon: 'none',
							duration: 3000
						})
					}
				})
				// #endif
			},
			
			resetLocation : function(){
				let that = this
				uni.showLoading({
					title: '定位中...',
					mask: true
				});
				this.mapContext.moveToLocation({
					longitude: this.longitude,
					latitude: this.latitude,
					complete : res => {
						uni.hideLoading();
						setTimeout(()=>{
							that.getAddressInfo(that.latitude, that.longitude)
						},500)
					}
				})
			},
			
			async searchLocAddress() {
				if (!this.keyword.trim()) {
					uni.showToast({
						title: '请输入搜索关键词',
						icon: 'none'
					})
					return;
				}
				
				if (!this.selectorCityName) {
					uni.showToast({
						title: '请先选择城市',
						icon: 'none'
					})
					return;
				}
				
				uni.showLoading({
					title: '搜索中...',
					mask: true
				});
				
				let that = this
				// #ifdef APP-PLUS || H5 
				const { code, data } = await getLocation({ region:this.selectorCityName,keyword:this.keyword,'policy':1,region_fix:1,});
				uni.hideLoading();
				if (code == 1) {
					if (data.data.length > 0) {
						that.$emit('addressUpdate', {'result' :data.data})
						let model = data.data[0];
						that.mapContext.moveToLocation({
							longitude: model.location.lng,
							latitude: model.location.lat,
							complete : res => {
								setTimeout(()=>{
									that.getAddressInfo(model.location.lat, model.location.lng)
								},500)
							}
						})
					} else {
						uni.showToast({
							title: "未找到相关地址",
							icon: 'none'
						})
					}
				}
				// #endif
				
				//#ifdef MP-WEIXIN
				// 调用接口
				this.qqmapsdk.getSuggestion({
					region : this.selectorCityName,
					keyword: this.keyword, //搜索关键词
					region_fix:1,
					policy:1,
					success(res) { //搜索成功后的回调
						uni.hideLoading();
						if (res.data.length > 0) {
							that.$emit('addressUpdate', {'result' :res.data})
							let model = res.data[0]
							that.mapContext.moveToLocation({
								longitude: model.location.lng,
								latitude: model.location.lat,
								complete : res => {
									setTimeout(()=>{
										that.getAddressInfo(model.location.lat, model.location.lng)
									},500)
								}
							})
						} else {
							uni.showToast({
								title: "未找到相关地址",
								icon: 'none'
							})
						}
					},
					fail: function(res) {
						uni.hideLoading();
						uni.showToast({
							title: "搜索失败",
							icon: 'none'
						})
					},
				});
				// #endif
			},			
			openPopup : function(){
				this.showPopup = true
			},
			
			closedPopup: function() {
				this.showPopup = false
			},
			regionChange(region) {				
				this.selectorCityName = region[2].label;
				this.keyAddress = region[0].label + " " + region[1].label + " " + region[2].label;
				this.searchLocAddress(); // 自动搜索所选城市
			},
		}
	}
</script>

<style lang="scss" scoped>	
	/* 变量定义 */
	$primary-color: #2979FF;
	$text-color: #333333;
	$border-color: #E6E6E6;
	$bg-color: #F8F8F8;
	$shadow: 0 2rpx 12rpx rgba(0,0,0,0.1);
	
	/* 地图容器 */
	.map-container {
		display: flex;
		flex-direction: column;
		background-color: $bg-color;
	}
	
	/* 地图区域 */
	.map-box {
		position: relative;
		width: 100%;
		border-radius: 0 0 24rpx 24rpx;
		overflow: hidden;
		box-shadow: $shadow;
		
		.map-content {
			width: 100%;
			display: block;
		}
		
		.center-marker {
			width: 48rpx;
			height: 48rpx;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			z-index: 10;
		}
		
		.control-panel {
			position: absolute;
			right: 30rpx;
			bottom: 30rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			
			.location-btn {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				background-color: #FFFFFF;
				box-shadow: $shadow;
				transition: transform 0.2s;
				
				&:active {
					transform: scale(0.95);
				}
			}
		}
	}
	
	/* 搜索栏 */
	.search-bar {
		display: flex;
		align-items: center;
		margin: 24rpx;
		padding: 0 24rpx;
		height: 88rpx;
		background-color: #FFFFFF;
		border-radius: 44rpx;
		box-shadow: $shadow;
		
		.city-selector {
			display: flex;
			align-items: center;
			padding: 0 10rpx;
			height: 60rpx;
			
			.city-text {
				font-size: 28rpx;
				color: $text-color;
				font-weight: 500;
				max-width: 160rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
			
			.city-arrow {
				font-size: 22rpx;
				color: #999999;
				margin-left: 6rpx;
			}
		}
		
		.divider {
			width: 2rpx;
			height: 40rpx;
			background-color: $border-color;
			margin: 0 20rpx;
		}
		
		.search-input {
			flex: 1;
			height: 88rpx;
			font-size: 28rpx;
			color: $text-color;
		}
		
		.placeholder {
			color: #999999;
			font-size: 28rpx;
		}
		
		.search-btn {
			height: 60rpx;
			background-color: $primary-color;
			border-radius: 30rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 0 30rpx;
			transition: background-color 0.2s;
			
			&:active {
				background-color: darken($primary-color, 5%);
			}
			
			.btn-text {
				color: #FFFFFF;
				font-size: 28rpx;
				font-weight: 500;
			}
		}
	}
	
	/* 弹窗样式 */
	.popup-wrapper {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;
		
		.popup-mask {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: rgba(0, 0, 0, 0.4);
		}
	}
</style>